import { ref } from 'vue';
import { defineStore } from 'pinia';

import { fetchUserPermission } from '@/apis/appuser';

const appMenusRouteTableTemplate = [
  /* 商品货架 */
  {
    name: '商品管理',
    path: '/commodity/manage',
    component: () => import('@/views/commodity/CommodityManage.vue'),
    alias: 'commodity'
  },
  {
    name: '分类管理',
    path: '/commodity/category',
    component: () => import('@/views/commodity/CommodityCategory.vue')
  },
  {
    name: '添加商品',
    path: '/commodity/add',
    component: () => import('@/views/commodity/CommodityAdd.vue')
  },
  {
    name: '编辑商品',
    path: '/commodity/edit',
    component: () => import('@/views/commodity/CommodityEdit.vue')
  },

  /* 订单中心 */
  {
    name: '订单管理',
    path: '/order/list',
    component: () => import('@/views/order/OrderList.vue'),
    alias: 'order'
  },

  /* 个人中心 */
  {
    name: '基本资料',
    path: '/user/profile',
    component: () => import('@/views/app_user/UserProfile.vue'),
    alias: 'user'
  },
  {
    name: '重置密码',
    path: '/user/password',
    component: () => import('@/views/app_user/UserPassword.vue')
  },

  /* 系统管理 */
  {
    name: '菜单管理',
    path: '/system-manage/menu',
    component: () => import('@/views/system-manage/SystemMenu.vue'),
    alias: 'system-manage'
  },
  {
    name: '角色管理',
    path: '/system-manage/role',
    component: () => import('@/views/system-manage/SystemRole.vue')
  },
  {
    name: '权限管理',
    path: '/system-manage/permission',
    component: () => import('@/views/system-manage/SystemPermission.vue')
  },

  /* 关于 */
  {
    name: '关于',
    path: '/about',
    component: () => import('@/views/framework/AboutPage.vue')
  }
];

let appMenusRouteTable = [];

export const useAppMenuStore = defineStore(
  'app-menu',
  () => {
    const appMenusInLevel = ref([]);
    const appMenus = ref([]);

    // 过滤掉不需要显示的菜单
    const filterTheMenu = (appMenus) => {
      let resultMenuArr = appMenus
        .map((a) => {
          return { ...a };
        })
        .filter((a) => a.menuIcon);

      appMenus
        .filter((a) => !a.menuIcon)
        .forEach((a) => {
          console.log(`菜单 ${a.menuName} 的图标未设置，因此不展示`);
        });

      resultMenuArr.forEach((menu) => {
        if (menu.children && menu.children.length > 0) {
          menu.children = filterTheMenu(menu.children);
        }
      });
      return resultMenuArr;
    };

    // 将菜单展平
    const flattenTheMenu = (appMenus) => {
      let resultMenuArr = [];
      appMenus.forEach((menu) => {
        let menuTemp = { ...menu };
        delete menuTemp.children;
        resultMenuArr.push(menuTemp);

        if (menu.children && menu.children.length > 0) {
          var childrenFlatMenus = flattenTheMenu(menu.children);
          resultMenuArr = resultMenuArr.concat(childrenFlatMenus);
        }
      });
      return resultMenuArr;
    };

    // 匹配路由模板中的项（名称和路径必须一致才能匹配）
    const resolveAppMenusRouteTable = (flatMenus) => {
      let flatNameArr = flatMenus.map((x) => x.menuName);
      let templateNameArr = appMenusRouteTableTemplate.map((x) => x.name);
      let appMenusRouteTable = appMenusRouteTableTemplate.filter((t) => {
        let index = flatNameArr.indexOf(t.name);
        if (index === -1) {
          return false;
        }

        if (t.path !== flatMenus[index].menuPath) {
          console.warn(
            `${t.name} 的路径与前端路由模板中的不匹配，前端路由模板中为：${t.path}，而获取的为：${flatMenus[index].menuPath}！`
          );
          return false;
        }

        return true;
      });

      // 未匹配到的项给出提示信息
      flatMenus
        .filter(
          (t) => templateNameArr.indexOf(t.menuName) === -1 && t.level !== 1
        )
        .forEach((t) =>
          console.warn(
            `未在前端路由模板中匹配到名称为： ${t.menuName} ，路径为： ${t.menuPath} 的项！`
          )
        );

      return appMenusRouteTable;
    };

    // 刷新菜单项
    const refreshAppMenus = async () => {
      let res = await fetchUserPermission();

      // 赋值层级菜单项
      appMenusInLevel.value = res.data;

      // 赋值菜单项
      appMenus.value = filterTheMenu(appMenusInLevel.value);

      // 赋值路由表
      let flatMenus = flattenTheMenu(appMenusInLevel.value);
      appMenusRouteTable = resolveAppMenusRouteTable(flatMenus);
    };

    const getLocalAppMenus = () => {
      return appMenus.value;
    };

    const getLocalAppMenusRouteTable = () => {
      if (appMenusRouteTable.length === 0) {
        let flatMenus = flattenTheMenu(appMenusInLevel.value);
        appMenusRouteTable = resolveAppMenusRouteTable(flatMenus);
      }
      return appMenusRouteTable;
    };

    return {
      appMenusInLevel,
      appMenus,
      filterTheMenu,
      refreshAppMenus,
      getLocalAppMenus,
      getLocalAppMenusRouteTable
    };
  },
  {
    persist: true
  }
);
